<!--
 * @Author:  kai
 * @Date: 2022-11-21 14:42:23
 * @LastEditTime: 2023-02-08 11:01:17
-->
<template>
  <div v-if="addsource" class="container">
    <div class="back_box" @click="handleBacklist()">
      <Icon
        type="md-arrow-round-back"
        color="white"
        :size="20"
        style="z-index: 999"
      />
    </div>
    <div class="add_Container">
      <div class="head">
        <div class="title">{{ title }}</div>
        <div class="edit"></div>
      </div>
      <div class="body">
        <!-- :rules="addFormrules" -->
        <Form
          ref="addForms"
          :model="editForm"
          :rules="ruleCustoms"
          inline
          label-position="top"
          class="Formbox"
        >
          <!-- 一 -->
          <Row :gutter="52">
            <Col :span="12">
              <FormItem label="Data source name" prop="dataSource">
                <div class="ipt">
                  <Input
                    type="text"
                    v-model="editForm.dataSource"
                    placeholder="please enter data source name"
                    :maxlength="500"
                  ></Input>
                </div>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="Description">
                <div class="ipt">
                  <Input
                    type="text"
                    v-model="editForm.description"
                    placeholder="please enter description"
                    :maxlength="1000"
                  ></Input>
                </div>
              </FormItem>
            </Col>
          </Row>
          <!-- 二 -->
          <Row :gutter="52">
            <Col :span="12">
              <FormItem label="User name">
                <div class="ipt">
                  <Input
                    type="text"
                    v-model="editForm.userName"
                    placeholder="please enter user name"
                    :maxlength="500"
                  ></Input>
                </div>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="Password">
                <div class="ipt">
                  <div class="ipt">
                    <Input
                      type="password"
                      v-model.trim="editForm.passwords"
                      placeholder="please enter password"
                      password
                      :maxlength="500"
                    ></Input>
                  </div>
                </div>
              </FormItem>
            </Col>
          </Row>
          <!-- 二 -->
          <Row :gutter="52">
            <Col :span="12">
              <FormItem label="Type" prop="eType">
                <div class="ipt">
                  <Select
                    v-model="editForm.eType"
                    default-label="MQTT"
                    filterable
                    @on-change="changeDataType"
                  >
                    <Option value="MQTT" label="MQTT">MQTT</Option>
                    <Option value="API" label="API">API</Option>
                  </Select>
                </div>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem
                label="Host"
                prop="host"
                :rules="
                  editForm.eType === 'MQTT'
                    ? {
                        required: true,
                        message: 'The Host cannot be empty',
                        trigger: 'blur',
                      }
                    : {}
                "
              >
                <div class="ipt">
                  <Input
                    type="text"
                    v-model="editForm.host"
                    placeholder="please enter IP address/url"
                    :maxlength="500"
                  ></Input>
                </div>
              </FormItem>
            </Col>
          </Row>
          <!-- 三、 -->
          <template v-if="editForm.eType === 'MQTT'">
            <Row :gutter="52">
              <Col :span="12">
                <FormItem
                  label="Port number"
                  prop="port"
                  :rules="
                    editForm.eType === 'MQTT'
                      ? {
                          required: true,
                          message: 'The port cannot be empty',
                          trigger: 'blur',
                        }
                      : {}
                  "
                >
                  <div class="ipt">
                    <Input
                      type="number"
                      v-model="editForm.port"
                      placeholder="please enter Port number"
                    ></Input>
                  </div>
                </FormItem>
              </Col>
              <Col :span="12">
                <FormItem
                  label="Topic"
                  prop="topic"
                  :rules="
                    editForm.eType === 'MQTT'
                      ? {
                          required: true,
                          message: 'The topic cannot be empty',
                          trigger: 'blur',
                        }
                      : {}
                  "
                >
                  <div class="ipt">
                    <Input
                      type="text"
                      v-model="editForm.topic"
                      placeholder="please enter subscribe to topics"
                      :maxlength="500"
                    ></Input>
                  </div>
                </FormItem>
              </Col>
            </Row>
            <!-- 四 -->
            <Row :gutter="52">
              <Col :span="12">
                <FormItem label="Source location">
                  <div class="ipt">
                    <Input
                      type="text"
                      v-model="editForm.sorceLocaltion"
                      placeholder="please enter source location"
                    ></Input>
                  </div>
                </FormItem>
              </Col>
              <Col :span="12">
                <FormItem label="Data decryption">
                  <div class="ipt uploading">
                    <i-switch
                      size="large"
                      v-model="editForm.dataDecryption"
                      @on-change="RadioChange()"
                    >
                      <span slot="open">YES</span>
                      <span slot="close">NO</span>
                    </i-switch>
                    <Input
                      v-if="editForm.dataDecryption === true"
                      type="text"
                      placeholder="Please upload certificate (.pem .pfx .crt)"
                      readonly
                      class="uploadinput"
                      @click.native="handleUpload()"
                      width="300"
                    ></Input>
                    <Tag
                      v-if="
                        file &&
                        editForm.dataDecryption == true &&
                        title !== 'Edit data source'
                      "
                      closable
                      @on-close="handelCloseTags()"
                      color="white"
                      >{{ formatterSourceName(this.file.name) }}</Tag
                    >
                    <!-- 回显标签 -->
                    <Tag
                      v-if="
                        editForm.certFile &&
                        editForm.dataDecryption == true &&
                        title !== 'Add data source'
                      "
                      closable
                      @on-close="handelDeletefiles()"
                      color="white"
                      >{{ formatterSourceName(this.editForm.certFile) }}</Tag
                    >
                    <input
                      type="file"
                      accept=".crt,.pem,.pfx"
                      @change="fileChange"
                      ref="myInput"
                      style="display: none"
                    />
                  </div>
                  <div v-if="file && loading">
                    <Progress
                      :percent="progressValue"
                      :stroke-width="5"
                      status="active"
                      text-inside
                    />
                  </div>
                </FormItem>
              </Col>
            </Row>
          </template>
          <!-- 三、 -->
          <template v-if="editForm.eType === 'API'">
            <Row :gutter="52">
              <Col :span="12">
                <FormItem
                  label="Client ID"
                  prop="clientID"
                  :rules="{
                    required: true,
                    message: 'The client id cannot be empty',
                    trigger: 'blur',
                  }"
                >
                  <div class="ipt">
                    <Input
                      type="text"
                      v-model="editForm.clientID"
                      disabled
                    ></Input>
                  </div>
                </FormItem>
              </Col>
              <Col :span="12">
                <FormItem
                  label="Client Secret"
                  prop="clientSecret"
                  :rules="{
                    required: true,
                    message: 'The client secret cannot be empty',
                    trigger: 'blur',
                  }"
                >
                  <div class="ipt">
                    <Input
                      type="text"
                      v-model="editForm.clientSecret"
                      :maxlength="500"
                      @on-change="changeDataSecret"
                    ></Input>
                  </div>
                </FormItem>
              </Col>
            </Row>
            <!-- 四 -->
            <FormItem
              label="Access Token"
              prop="accessToken"
              :rules="
                editForm.eType === 'API'
                  ? {
                      required: true,
                      message: 'The access token cannot be empty',
                      trigger: 'blur',
                    }
                  : {}
              "
            >
              <div class="ipt">
                <Input
                  type="textarea"
                  v-model="editForm.accessToken"
                  :rows="3"
                  disabled
                ></Input>
              </div>
            </FormItem>
            <!-- 四 -->
            <FormItem label="API Post URL">
              <div class="ipt">
                <Input type="text" v-model="postAPIURL" disabled></Input>
              </div>
            </FormItem>
          </template>
          <!-- 五 -->
          <Row :gutter="52">
            <Col :span="12">
              <FormItem label="Enable">
                <i-switch size="large" v-model="editForm.enabled">
                  <span slot="open">true</span>
                  <span slot="close">false</span>
                </i-switch>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <div class="foot">
        <div
          class="leftBtn"
          :class="activeBtn === 'Cancel' ? 'activeBtnClass' : ''"
          @click="handleBacklist(), (activeBtn = 'Cancel')"
        >
          Cancel
        </div>
        <div
          class="rightBtn"
          @click="(activeBtn = 'Confirm'), handleAddOrEdit()"
          :class="activeBtn === 'Confirm' ? 'activeBtnClass' : ''"
        >
          Confirm
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// import AWS_FUNCTIONS from "../../../config/AWSS3";

export default {
  data() {
    return {
      fileName: "",
      loading: true,
      fileKey: "",
      SourceID: null,
      file: null,
      progressValue: 0,
      activeBtn: "Confirm",
      title: "Add data source",
      addsource: false,
      S3filekey: "",
      S3bucket: "",
      editForm: {
        dataSource: "",
        description: "",
        eType: "API",
        host: "",
        port: 0,
        sorceLocaltion: "",
        topic: "",
        dataDecryption: true,
        userName: "",
        passwords: "",
        projectId: "",
        enabled: "false",
        // 新增API配置
        clientID: "",
        clientSecret: "",
        accessToken: "",
      },
      ruleCustoms: {
        dataSource: [
          {
            required: true,
            message: "The data Source name cannot be empty",
            trigger: "blur",
          },
        ],
        eType: [
          {
            required: true,
            message: "The type cannot be empty",
            trigger: "blur",
          },
        ],
      },
      // 新增API POST 请求地址
      postAPIURL:
        "https://trial_iot_api.app.saas.neuroncloud.ai/api/InfluxDBClient/IotHub",
    };
  },
  methods: {
    // 点击触发隐藏的input file
    handleUpload() {
      this.$refs.myInput.click();
    },
    handleopen(id) {
      this.activeBtn = "Confirm";
      this.addsource = true;
      if (id) {
        this.title = "Edit data source";
        this.SourceID = id;
        this.GetPreviewByid(id);
      } else {
        this.title = "Add data source";
        this.editForm = {
          dataSource: "",
          description: "",
          eType: "MQTT",
          host: "",
          port: "",
          sorceLocaltion: "",
          topic: "",
          dataDecryption: "true",
          userName: "",
          passwords: "",
          projectId: "",
          enabled: "false",
          // 新增API配置
          clientID: "",
          clientSecret: "",
          accessToken: "",
        };
      }
    },
    formatterSourceName(name) {
      if (name) {
        if (name.length >= 10) {
          const newName = `${name.slice(0, 10)}...`;
          return newName;
        }
        return name;
      }
      return true;
    },
    /** 返回list列表 */
    handleBacklist() {
      this.S3filekey = "";
      const str = "Confirm";
      this.S3bucket = str;
      this.activeBtn = str;
      this.addsource = false;
      this.$emit("handleshow", true);
    },
    /** 编辑目标ID */
    GetPreviewByid(id) {
      const url = `${ROUTER.LoraWan2DBConfig.operate}/${id}`;
      this.$http.get(url, this.editForm).then((res) => {
        console.log(
          "----------------------- EditSourceByid -----------------------"
        );
        if (res.data.isSuccess) {
          console.log("更新目标", res.data.data);
          this.editForm = res.data.data;
          this.editForm.dataDecryption =
            this.editForm.dataDecryption.toString();
          this.editForm.enabled = this.editForm.enabled.toString();
          this.editForm.port = this.editForm.port.toString();
          this.S3filekey = this.editForm.s3KeyOfCertFile;
          this.accessToken = this.editForm.accessToken;
          this.clientID = this.editForm.clientID;
          this.clientSecret = this.editForm.clientSecret;
        }
      });
    },
    /** Data decryption 单选框判断如果不加密则 false */
    RadioChange() {
      if (this.editForm.dataDecryption === "false") {
        this.fileName = "";
        this.S3filekey = "";
        this.editForm.certFile = "";
        this.editForm.s3KeyOfCertFile = "";
      }
    },
    /** 上传文件  更新时再次点击上传时,把回显文件标签删除 */
    fileChange(_e) {
      const e = _e;
      const { files } = e.target;
      const [file] = files;
      this.file = file;
      this.fileName = this.file.name;
      console.log("上传文件", e);
      /** 编辑时的 certname 更新 */
      this.editForm.certFile = this.fileName;
      this.Uploadfiles(this.file);
      e.target.value = "";
    },
    // 上传文件
    // CREAGEIMGKEYS(); 全局方法生成keys
    /** Upload to S3 */
    Uploadfiles(formData) {
      this.fileKey = window.CREAGEIMGKEYS();
      AWS_FUNCTIONS.UPLOAD_FILE_AWS_S3S(
        this.fileKey,
        formData,
        this.progressCallback
      )
        .then((res) => {
          if (res.isSuccess) {
            console.log("S3", res);
            this.$Message.success("uploadfileSuccessfully");
            this.S3filekey = res.data.key;
            /** 编辑时的 S3key 更新 */
            this.editForm.s3KeyOfCertFile = this.S3filekey;
            this.S3bucket = res.data.Bucket;
            this.loading = false;
          }
        })
        .catch((err) => {
          this.$Message.error("file upload failed, please try again later");
          console.log(`fileUploadErr: ${err.toString()}`);
        });
    },
    /** Close Tag */
    handelCloseTags() {
      this.file = null;
      this.S3filekey = "";
      this.S3bucket = "";
    },
    /** 编辑时 关闭标签代表删除该标签 */
    handelDeletefiles() {
      this.editForm.certFile = "";
      this.editForm.s3KeyOfCertFile = "";
      this.S3bucket = "";
      this.editForm.dataDecryption = "false";
    },
    /** 进度条 */
    progressCallback(e) {
      const precent = parseInt(e.loaded, 10) / parseInt(e.total, 10);
      this.progressValue = precent * 100;
    },
    /** 添加请求 */
    handleAddDataSource() {
      console.log("添加请求query", this.$route.query.projectId);
      this.$refs.addForms.validate((valid) => {
        const creator = window.sessionStorage.getItem("username");
        if (valid) {
          const url = ROUTER.LoraWan2DBConfig.operate;
          const {
            dataSource,
            description,
            eType,
            host,
            port,
            sorceLocaltion,
            topic,
            dataDecryption,
            userName,
            passwords,
            enabled,
            clientID,
            clientSecret,
            accessToken,
          } = this.editForm;
          const params = {
            projectId: this.$route.query.projectId,
            dataSource,
            description,
            eType,
            clientID,
            clientSecret,
            host,
            port: window.parseInt(port) || 0,
            topic,
            latitude: 0,
            longitude: 0,
            sorceLocaltion,
            dataDecryption: JSON.parse(dataDecryption),
            certFile: this.fileName || "",
            s3KeyOfCertFile: this.S3filekey || "",
            accessToken,
            userName: userName || "",
            passwords: passwords || "",
            enabled: JSON.parse(enabled),
            creatorUserID: creator,
            updateUserID: creator,
          };
          console.log("添加请求的数据", params);
          this.$http.post(url, params).then((res) => {
            console.log(
              "----------------------- handleAddDataSource -----------------------"
            );
            if (res.data.isSuccess) {
              this.$Message.success(res.data.title);
              this.file = null;
              this.S3filekey = "";
              this.S3bucket = "";
              this.handleBacklist();
            } else {
              this.$Message.error("Add Fail!");
            }
          });
        } else {
          this.$Message.error("Fail!");
        }
      });
    },
    /** 更新请求 */
    handleUpdataDataSource(id) {
      this.$refs.addForms.validate((valid) => {
        const creator = window.sessionStorage.getItem("username");
        if (valid) {
          const url = `${ROUTER.LoraWan2DBConfig.Update}/${id}`;
          const {
            dataSource,
            description,
            eType,
            host,
            port,
            sorceLocaltion,
            topic,
            dataDecryption,
            userName,
            passwords,
            enabled,
          } = this.editForm;
          const query = {
            id,
            projectId: this.$route.query.projectId,
            dataSource,
            description,
            eType,
            host,
            port: window.parseInt(port),
            topic,
            sorceLocaltion,
            dataDecryption: JSON.parse(dataDecryption),
            certFile: this.editForm.certFile || "",
            s3KeyOfCertFile: this.editForm.s3KeyOfCertFile || "",
            Bucket: this.S3bucket || "",
            userName: userName || "",
            passwords: passwords || "",
            creatorUserID: creator,
            updateUserID: creator,
            enabled: JSON.parse(enabled),
          };
          console.log("更新请求的数据", query);
          this.$http.post(url, query).then((res) => {
            console.log(
              "----------------------- handleAddDataSource -----------------------"
            );
            if (res.data.isSuccess) {
              this.$Message.success("Successfully Updated");
              this.addsource = false;
              this.file = null;
              this.S3filekey = "";
              this.S3bucket = "";
              this.$emit("handleshow");
            } else {
              this.$Message.error("Falied Updated");
            }
          });
        } else {
          this.$Message.error("Fail!");
        }
      });
    },
    /** 点击Confirm按钮 判断是 添加 / 修改 */
    handleAddOrEdit() {
      // 新增自动填入Client ID为当前登录用户ID
      this.changeDataType();
      if (this.title === "Add data source") {
        /** 判断如果 Datadecrytion 为true 状态 必须上传文件 才能发送添加请求. */
        if (this.editForm.dataDecryption === true) {
          if (this.S3filekey) {
            this.handleAddDataSource();
          } else {
            this.$Message.error(
              "If you Choose Data decryption Please upload your files before add the Data Source !"
            );
          }
        } else {
          this.handleAddDataSource();
        }
      } else {
        const id = this.SourceID;
        if (this.editForm.dataDecryption === "true") {
          if (this.S3filekey) {
            this.handleUpdataDataSource(id);
          } else {
            this.$Message.error(
              "If you Choose Data decryption Please upload your files before Update the Data Source !"
            );
          }
        } else {
          this.handleUpdataDataSource(id);
        }
      }
    },
    /** 选择API时，自动填入Client ID */
    changeDataType() {
      if (this.editForm.eType === "API" && !this.editForm.clientID) {
        const userInfo = JSON.parse(sessionStorage.getItem("userInfo") || "{}");
        this.$set(this.editForm, "clientID", userInfo.sub);
      }
    },
    changeDataSecret() {
      const token =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
      this.$set(
        this.editForm,
        "accessToken",
        token + this.editForm.clientSecret
      );
    },
  },
  mounted() {
    this.activeBtn = "Confirm";
  },
};
</script>
<style scoped lang="less">
.container {
  .back_box {
    width: 32px;
    height: 32px;
    background-color: #000000;
    margin-left: 20px;
    margin-bottom: 16px;
    text-align: center;
    line-height: 32px;
  }
  .add_Container {
    width: 97%;
    margin-left: 20px;
    display: flex;
    flex-direction: column;
    background: linear-gradient(
      180deg,
      rgba(20, 49, 46, 0.95) 17.25%,
      rgba(46, 64, 62, 0.45) 122.26%
    );
    padding: 20px 28px 0 24px;
    .head {
      display: flex;
      justify-content: space-between;
      color: white;
      // height: 5%;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      padding: 15px 28px 20px 16px;
      .title {
        width: 126px;
        height: 23px;
        font-weight: 700;
        font-size: 16px;
        line-height: 23px;
      }
    }
    .body {
      height: 90%;
      .Formbox {
        /** Data decryption 的样式 */
        .uploading {
          /** 选中颜色 */
          .ivu-radio-group-button-solid
            .ivu-radio-wrapper-checked:not(.ivu-radio-wrapper-disabled) {
            background: #22ffe5 !important;
            color: #08141d;
          }
          .ivu-radio-group-button {
            background-color: black !important;
            border-radius: 10px;
            padding: 5px;
          }
          .ivu-radio-group-button .ivu-radio-wrapper {
            background: black !important;
            border: none !important;
            border-radius: 10px;
            width: 72px;
            height: 28px;
          }
          .ivu-radio-group-button .ivu-radio-wrapper-checked:first-child {
            border-color: none !important;
          }
        }

        margin-top: 28px;
        /** input & select-input 样式修改 */
        /deep/.ivu-form-item {
          input[type="number"] {
            -moz-appearance: textfield;
          }
          input[type="number"]::-webkit-inner-spin-button,
          input[type="number"]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
          }
          width: 100% !important;
          .ivu-input {
            background: #041622 !important;
            padding-left: 10px;
            padding-right: 10px;
          }
          .ivu-select-input {
            background: #041622 !important;
          }
        }
        .uploading {
          display: flex;
          align-items: center;
          /** Data */
          .uploadinput {
            width: 60%;
            margin-left: 30px;
            cursor: pointer;
            /deep/.ivu-input {
              color: #22ffe5 !important;
            }
          }
          .ivu-tag {
            // width: 132px;
            height: 32px;
            line-height: 32px;
            margin-left: 10px;
            border-radius: 24px !important;
            background: #225858 !important;
            border: none !important;
            text-decoration: underline;
            .ivu-icon-ios-close {
              font-size: 20px !important;
            }
          }
        }
      }
      .purple_color {
        background: #041622 !important;
      }
      .enabled {
        .ivu-radio-group-button {
          box-sizing: border-box;
          background-color: #041622;
          border-radius: 10px !important;
          padding-left: 5px;
          padding-right: 5px;
        }
        .ivu-radio-group-button-solid
          .ivu-radio-wrapper-checked:not(.ivu-radio-wrapper-disabled) {
          background: #22ffe5 !important;
          color: #08141d;
        }
        .ivu-radio-group-button-solid
          .false_choise
          .ivu-radio-wrapper-checked:not(.ivu-radio-wrapper-disabled) {
          background: gray !important;
          color: #08141d;
        }
        .ivu-radio-group-button .ivu-radio-wrapper {
          border: none;
          background: #041622 !important;
          border-radius: 5px !important;
          border-right: none !important;
          width: 72px !important;
          height: 15px !important;
          font-size: 0;
        }
      }
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    .foot {
      display: flex;
      height: 10%;
      justify-content: center;
      align-items: center;
      padding-top: 24px;
      padding-bottom: 48px;
      .rightBtn,
      .leftBtn {
        cursor: pointer;
        width: 148px;
        height: 40px;
        font-size: 16px;
        border-radius: 4px;
        text-align: center;
        line-height: 40px;
        color: #b3b3b3;
        background-color: #1c2424;
      }
      .rightBtn {
        margin-left: 48px;
      }
      .activeBtnClass {
        width: 148px;
        height: 40px;
        background-color: #22ffe5;
        color: #171717;
      }
    }
  }
}
</style>
